package space.xxhui.forcelist.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

import space.xxhui.forcelist.R;
import space.xxhui.forcelist.impclass.RecycleItemTouchHelper;

import static android.content.ContentValues.TAG;

/**
 * Created by hui on 2016/5/16.
 */
public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements RecycleItemTouchHelper.Callback {

    private List<String> data;//textview的显示的字符串数据
    private OnItemClickListener clickListener;//给RecyclerView添加点击事件

    public Adapter(List<String> data) {
        this.data = data;
    }//初始化时注入数据

    public void setOnItemClickListener(OnItemClickListener itemClickListener){//设置注入item点击监听
        clickListener = itemClickListener;
    }

    /**
     * 解析布局，并注入到viewHolder
     * @return 给下一步提供一个ViewHolder
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
        return new ViewHolder(v);
    }

    /**
     * 给ViewHolder里面的控件绑定数据
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((ViewHolder)holder).textView.setText(data.get(position)+position);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }



    /**
     * 内部类ViewHolder，用于保存绑定控件，如果设置了点击事件，给控件设置点击监听
     */
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        private TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
            textView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(clickListener!=null){
                clickListener.onItemClick(v,getPosition());
            }
        }
    }

    @Override
    public void onItemDelete(int positon) {
        data.remove(positon);
        notifyItemRemoved(positon);
    }

    @Override
    public void onMove(int fromPosition, int toPosition) {
        Collections.swap(data,fromPosition,toPosition);//交换数据
        notifyItemMoved(fromPosition,toPosition);
    }

    /**
     * 定义一个接口用于外部实现RecycleView的item的操作
     */
    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }
}
